package tech.mhuang.pacebox.sms;

import lombok.extern.slf4j.Slf4j;
import tech.mhuang.pacebox.core.chain.BaseChain;
import tech.mhuang.pacebox.core.chain.ChainAdapter;
import tech.mhuang.pacebox.sms.domain.SmsSendRequest;
import tech.mhuang.pacebox.sms.domain.SmsSendResult;
import tech.mhuang.pacebox.sms.inteceptor.SmsSendInterceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 短信模板
 *
 * @author mhuang
 * @since 1.0.0
 */
@Slf4j
public class SmsTemplate implements SmsOperation {

    /**
     * 具体配置了多少个短信处理器(发送时进行指定）
     */
    private Map<String, BaseSmsHandler> smsHandlerMap = new ConcurrentHashMap<>();

    /**
     * 拦截器（用于在消息开始和结束、异常前改变消息、以及可用于短信埋点）
     */
    private List<SmsSendInterceptor> interceptors = new CopyOnWriteArrayList<>();

    @Override
    public void addHandler(String key, BaseSmsHandler smsHandler) {
        smsHandlerMap.put(key, smsHandler);
    }

    @Override
    public void addInteceptor(SmsSendInterceptor sendInterceptor) {
        interceptors.add(sendInterceptor);
    }


    public void setInterceptors(List<SmsSendInterceptor> smsSendInterceptors) {
        this.interceptors = smsSendInterceptors;
    }

    /**
     * 发送短信
     *
     * @param smsSendRequest 短信请求参数
     * @return 短信发送结果
     */
    @Override
    public SmsSendResult send(SmsSendRequest smsSendRequest) {
        return doSend(smsSendRequest);
    }

    /**
     * 开始发送短信
     *
     * @param smsSendRequest 短信请求参数
     * @return 短信发送结果
     */
    protected SmsSendResult doSend(SmsSendRequest smsSendRequest) {
        List<SmsSendInterceptor> interceptorList = new ArrayList<>();
        interceptorList.addAll(interceptors);
        //最后执行短信模板调用
        interceptorList.add(new SmsSendInterceptor.Standard(smsHandlerMap));
        BaseChain<SmsSendRequest, SmsSendResult> chain = new ChainAdapter(interceptorList, 0, smsSendRequest);
        return chain.proceed(smsSendRequest);
    }
}